import React, { Component } from 'react';
import {
  Select,
  Form,
  Card,
  Button,
  Row,
  Col,
  Table,
  Divider,
  Tag,
  Input,
  DatePicker,
  Pagination,
  message,
  Tooltip,
  Icon,
} from 'antd';
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
import moment from 'moment';

import FileUpload from './FileUpload';
import importPngFlag from '@/assets/import.png';
import ModificationButton from './ModificationButton';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import style from './index.css';
import { saveAs } from 'file-saver';
import followUpList from '@/assets/followUpList.png';
import PermissionsWidget from '@/components/PermissionsWidget';
import UploadComponent from '@/components/UploadComponent';

@connect(({ user, followUpList, loading }) => ({
  currentUser: user.currentUser,
  data: followUpList.data,
  isDownLoading: loading.effects['followUpList/queryAllExportData'],
}))
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      expand: false,
      data: [],
      total: 0,
      current: 0,
      ids: [],
      form: {},
      cityIdData: [],
      districtIdData: [],
      countyIdData: [],
      villageIdData: [],
      sexData: [
        { id: '男', name: '男' },
        { id: '女', name: '女' },
      ],
      qualifiedData: [
        { id: '1', name: '合格' },
        { id: '2', name: '不合格' },
      ],
    };
  }
  cityIdChange = value => {
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  districtIdChange = value => {
    this.setState(
      params => ({
        form: {
          ...params.form,
          districtId: value,
        },
      }),
      () => {
        this.getCity({ level: 4, parentCode: value });
      }
    );
  };
  countyIdChange = value => {
    this.setState(
      params => ({
        form: {
          ...params.form,
          countyId: value,
        },
      }),
      () => {
        this.getCity({ level: 5, parentCode: value });
      }
    );
  };

  villageIdChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        villageId: value,
      },
    }));
  };
  institutionNameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        institutionName: value,
      },
    }));
  };
  nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        name: value,
      },
    }));
  };
  sexChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        sex: value,
      },
    }));
  };

  phoneChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        phone: value,
      },
    }));
  };
  sfzChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sfz: value,
      },
    }));
  };
  qualifiedChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        qualified: value,
      },
    }));
  };

  componentDidMount() {
    this.getDataByPage({});
    this.getCity({ level: 2, parentCode: '34' });
  }
  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        } else if (param.level == 4) {
          this.setState({
            countyIdData: resp.data,
          });
        } else if (param.level == 5) {
          this.setState({
            villageIdData: resp.data,
          });
        }
      }
    });
  };

  //分页切换
  onChangePagination = (page, pageSize) => {
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: page,
      pageSize: pageSize,
      ...this.state.form,
    });
  };
  onShowSizeChange = (current, pageSize) => {
    if (current === 0) {
      current = 1;
    }
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: current,
      pageSize: pageSize,
      ...this.state.form,
    });
  };

  //分页
  getDataByPage = param => {
    this.execHttp('followUpList/selList', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 10,
      ...param,
    }).then(resp => {
      if (resp.success) {
        this.setState({
          data: resp.data.list,
          total: resp.data.pagination.total,
          current: resp.data.pagination.current,
        });
      }
    });
  };
  onSelectChange = selectedRowKeys => {
    this.setState({ ids: selectedRowKeys });
  };

  //存入正式库
  add = () => {
    if (this.state.ids.length != 0) {
      const ids = this.state.ids.join('|');
      this.execHttp('followUpList/add', { data: ids }).then(resp => {
        if (resp.success) {
          message.success(resp.message);
          this.getDataByPage();
          this.setState({ ids: [] });
        } else {
          message.error(resp.message);
          this.setState({ ids: [] });
        }
      });
    } else {
      this.successMessage('请勾选需要存入正式库数据');
    }
  };

  // 导出
  exportData = () => {
    const ids = this.state.ids.join('|');
    const hide = this.loadingMessage('正在导出数据，请稍后...');
    this.execHttp('followUpList/queryAllExportData', {
      user: this.props.currentUser.id,
      ids: ids,
      ...this.state.form,
    })
      .then(res => {
        hide();
        saveAs(res, '详细数据上报' + '.xlsx');
      })
      .catch(err => {
        hide();
      });
  };
  //查询
  searchClick = () => {
    this.getDataByPage(this.state.form);
  };

  //重置
  resetClick = () => {
    this.setState(
      () => ({
        form: {},
      }),
      () => {
        this.getDataByPage(this.state.form);
      }
    );
  };

  //展开与否状态切换
  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  ruleDownload = () => {
    const a = document.createElement('a');
    a.target = '_blank';
    a.href = followUpList;
    a.click();
  };

  render() {
    const columns = [
      {
        title: '',
        dataIndex: 'country_source',
        key: 'country_source',
        width: 1,
        render: (text, record) => {
          const { country_source } = record;

          // 根据country_source的值生成对应的图片元素
          let imageElement = null;

          if (country_source === '1') {
            imageElement = <img src={importPngFlag} alt="国家系统数据" title="导入" />;
          }

          // 返回包含图片元素和文本内容的行元素
          return <div>{imageElement}</div>;
        },
      },
      {
        title: '是否合格',
        dataIndex: 'qualified',
        key: 'qualified',
        width: 100,
        render: (text, record, index) => {
          const { qualified, error_message } = record;
          if (qualified == 1) {
            return (
              <div className={style.successBox}>
                <span>合格</span>
              </div>
            );
          } else if (qualified == 5) {
            const arr = record.error_message ? record.error_message.split('|') : [];
            const messages = arr.map((item, index) => {
              return <div key={index}>{`${index + 1}.${item}`}</div>;
            });
            return (
              <div className={style.returnBox}>
                <span>退回</span>
                <Tooltip placement="top" title={<div>{messages}</div>}>
                  <Icon type="exclamation-circle" style={{ marginTop: '2px' }} />
                </Tooltip>
              </div>
            );
          } else {
            const arr = error_message ? error_message.split('|') : [];
            const messages = arr.map((item, index) => {
              return <div key={index}>{`${index + 1}.${item}`}</div>;
            });
            return (
              <div className={style.errorBox}>
                <span>不合格</span>
                <Tooltip placement="top" title={<div>{messages}</div>}>
                  <Icon type="exclamation-circle" style={{ marginTop: '2px' }} />
                </Tooltip>
              </div>
            );
          }
        },
      },
      {
        title: '村',
        dataIndex: 'village_name',
        key: 'village_name',
      },
      {
        title: '系统唯一识别码',
        dataIndex: 'screening_id',
        key: 'screening_id',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '联系电话',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '内镜诊疗日期',
        dataIndex: 'njzl_time',
        key: 'njzl_time',
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        render: (text, record, index) => {
          const { create_time } = record;
          const str = moment(create_time).format('YYYY-MM-DD');
          return str;
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <div>
            <ModificationButton record={record} getDataByPage={this.getDataByPage} />
          </div>
        ),
      },
    ];

    const { data, total, current } = this.state;
    const rowSelection = {
      selectedRowKeys: this.state.ids, // 同步选中的行数据
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <Card size="small" style={{ width: '100%' }} bordered={true} title={'随访列表'}>
          <Form layout="horizontal">
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.cityId}
                    onChange={this.cityIdChange}
                    placeholder="请选择所属城市"
                  >
                    {this.state.cityIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.districtId}
                    onChange={this.districtIdChange}
                    placeholder="请选择所属区/县"
                  >
                    {this.state.districtIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.countyId}
                    onChange={this.countyIdChange}
                    placeholder="请选择所属乡镇"
                  >
                    {this.state.countyIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6} style={{ textAlign: 'center' }}>
                <FileUpload getDataByPage={this.getDataByPage}></FileUpload>
                <Button
                  type="primary"
                  style={{ marginLeft: '5px', marginRight: '5px' }}
                  onClick={this.exportData}
                >
                  导出
                </Button>
                <Button type="primary" onClick={this.searchClick}>
                  查询
                </Button>
                <Button onClick={this.resetClick} style={{ marginLeft: '5px' }}>
                  重置
                </Button>
                <a style={{ marginLeft: 5, fontSize: 10 }} onClick={this.handleToggle}>
                  {this.state.expand ? '折叠' : '展开'}
                  <Icon type={this.state.expand ? 'up' : 'down'} />
                </a>
              </Col>
            </Row>

            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.villageId}
                    onChange={this.villageIdChange}
                    placeholder="请选择所属村"
                  >
                    {this.state.villageIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="机构名称"
                    value={this.state.form.institutionName}
                    onChange={this.institutionNameChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="姓名"
                    value={this.state.form.name}
                    onChange={this.nameChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.sex}
                    onChange={this.sexChange}
                    placeholder="请选择性别"
                  >
                    {this.state.sexData.map(item => (
                      <Select.Option key={item.id}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="电话"
                    value={this.state.form.phone}
                    onChange={this.phoneChange}
                  />
                </Form.Item>
              </Col>
              {/* <Col span={6}>
                <Form.Item label="申请签订日期">
                  <RangePicker style={{ width: 200 }} />selfSignDateStart  selfSignDateEnd
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="内镜诊疗日期">
                  <RangePicker style={{ width: 200 }} />njzlTimeBegin  njzlTimeEnd
                </Form.Item>
              </Col> */}
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="身份证号"
                    value={this.state.form.sfz}
                    onChange={this.sfzChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.qualified}
                    onChange={this.qualifiedChange}
                    placeholder="请选择是否合格"
                  >
                    {this.state.qualifiedData.map(item => (
                      <Select.Option key={item.id}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            {/* <Row>
              <Col span={24} style={{ textAlign: 'right' }}>
              <FileUpload getDataByPage={this.getDataByPage}></FileUpload>
                <Button
                  type="primary"
                  style={{ marginLeft: '10px', marginRight: '10px' }}
                  onClick={this.exportData}
                >
                  导出
                </Button>
                <Button type="primary" onClick={this.searchClick}>
                  查询
                </Button>
                <Button onClick={this.resetClick} style={{ marginLeft: '10px' }}>
                  重置
                </Button>
                <a style={{ marginLeft: 5, fontSize: 10 }} onClick={this.handleToggle}>
                  {this.state.expand ? '折叠' : '展开'}
                  <Icon type={this.state.expand ? 'up' : 'down'} />
                </a>
              </Col>
            </Row> */}
          </Form>
          <Button type="primary" onClick={this.ruleDownload}>
            校验规则下载
          </Button>
          <PermissionsWidget tag={'followUpList:follow-deposit'}>
            <Button type="primary" onClick={this.add} style={{ marginLeft: "10px" }}>存入正式表</Button>
          </PermissionsWidget>

          <Table
            columns={columns}
            dataSource={data}
            rowSelection={rowSelection}
            rowKey="id"
            pagination={false}
            size="small"
            style={{marginTop:'20px'}}
          />
          <div
            style={{
              marginTop: '20px',
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <Pagination
              showSizeChanger={true}
              showQuickJumper
              onChange={this.onChangePagination}
              onShowSizeChange={this.onShowSizeChange}
              defaultCurrent={1}
              current={current}
              total={total}
              showTotal={total => `总共 ${total} 条`}
            />
          </div>
        </Card>
        {/* <Card style={{ width: '100%', marginTop: '20px' }}>
          <Button type="primary" onClick={this.ruleDownload}>
            校验规则下载
          </Button>
          <PermissionsWidget tag={'followUpList:follow-deposit'}>
            <Button type="primary" onClick={this.add} style={{ marginLeft: "10px" }}>存入正式表</Button>
          </PermissionsWidget>

          <Table
            columns={columns}
            dataSource={data}
            rowSelection={rowSelection}
            rowKey="id"
            pagination={false}
            size=''
          />
          <div
            style={{
              marginTop: '20px',
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <Pagination
              showSizeChanger={true}
              showQuickJumper
              onChange={this.onChangePagination}
              onShowSizeChange={this.onShowSizeChange}
              defaultCurrent={1}
              current={current}
              total={total}
              showTotal={total => `总共 ${total} 条`}
            />
          </div>
        </Card> */}
      </div>
    );
  }
}
